﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    public static class ApiLogin
    {
        /// <summary>
        /// 根据token登录
        /// </summary>
        /// <param name="token"></param>
        /// <param name="email"></param>
        /// <param name="host">域名</param>
        /// <returns></returns>
        public static async Task<bool> TokenLogin(string token, string email,string host)
        {
            bool result = false;
            if (email.IsIpAddress())
            {
                result = true;
                return result;
            }
            if (AppSetting.IsNeedValid)
            {
                if (!string.IsNullOrEmpty(token))
                {
                    if (string.IsNullOrEmpty(email))
                    {
                        string webhost = host;
                        email = webhost.Match(@"[a-zA-Z0-9-]+.(com|org|net)?.(com|cn|net|org|biz|info|cc|tv|top|vip)");
                    }
                    string url = ConfigHelper.Configuration["TokenLoginApiUrl"];
                    HttpClient _client = new HttpClient();

                    var body = new { websiteToken = token, email = email, token = "ZjA1NzZlMmMxYzIOTg3MjBzNjYTI2MjA4Yw" }.ToJson();
                    var apiData = await _client.PostAsync(url, new StringContent(body, Encoding.UTF8, "application/json"));
                    string resultStr = await apiData.Content.ReadAsStringAsync();
                    if (!string.IsNullOrEmpty(resultStr))
                    {
                        bool isPass = resultStr.ToBoolean(false);
                        result = isPass;
                    }
                }
            }
            else
            {
                result = true;
            }
            return result;
        }
    }
}
